<template>
	<el-main class="bg table_wrap order">
	  <!-- 头部检索 -->
	  <div class="div-form">
		<el-form
		  ref="elFormRef"
		  :model="formInline"
		  label-width="90px"
		  :style="{ width: '100%' }"
		  label-position="left"
		>
		<el-row class="rows row1">
				<el-col :xs="24" :sm="12" :lg="6" class="el_form_search_wrap">
					<el-form-item label="订单号">
						<el-input v-model="formInline.order_number"></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :lg="6" class="el_form_search_wrap">
					<el-form-item label="商品名称">
						<el-input v-model="formInline.title"></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :lg="6" class="el_form_search_wrap">
					<el-form-item label="联系人姓名">
						<el-input v-model="formInline.contact_name"></el-input>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="12" :lg="6" class="el_form_search_wrap">
					<el-form-item label="状态">
						<el-select v-model="formInline.state">
							<el-option :key="-1" :value="0" :label="'无'"></el-option>
							<el-option v-for="(o,i) in list_state" :key="i" :value="o" :label="o">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				</el-row>
		</el-form>
	  </div>
	  <baseTable
		:tableColumns="columns"
		:requestApi="url_get_list"
		:vm="vm" 
		:isShowSelect="true"
		v-model:isRefresh="isRefresh"
		:otherParams="formInline"
		@handleSelectionChange="handleSelectionChange"
		@handleCurrentChangeNew="handleCurrentChangeNew"
	  >
		<!-- 头部按钮 -->
		<template #baseHeadFunt>
		  <el-button type="primary" @click="onSubmit">查询</el-button>
		  <el-button @click="onReset(true)">重置</el-button>
		  <el-button type="danger" class="search_btn_del" @click="delInfo()"
		  v-if="user_group == '管理员' || $check_action('/order/table','del')"
			>删除</el-button
		  >
		</template>
		<!-- 操作 -->
		<template #baseTableFunt="{ scope }">
		  <el-button
			type="primary"
			size="small"
			@click="router.push('./view?' + field + '=' + scope.row.order_id)"
			>详情</el-button
		  >
		  <el-button v-if="scope.row['state'] == '已付款' && scope.row['delivery_state'] == '未配送'" 
		  class="e-button el-button--small is-plain el-button--primary"
						@click="addLogi(scope.row)" size="small">
						配送
					
		</el-button>
		<!-- <el-button v-if="scope.row['state'] == '待付款' && scope.row['delivery_state'] == '未配送'" 
		  class="e-button el-button--small is-plain el-button--primary"
						@click="toPay(scope.row)" size="small">
						支付
					
		</el-button> -->
		</template>
		<!-- 操作 -->
		<template #baseTableFunt2="{ scope }">
		  <el-button
			type="primary"
			size="small"
			@click="router.push('./view?' + field + '=' + scope.order_id)"
			>详情</el-button
		  >
		  <el-button v-if="scope['state'] == '已付款' && scope['delivery_state'] == '未配送'" 
		  class="e-button el-button--small is-plain el-button--primary"
						@click="addLogi(scope)" size="small">
						配送
					
		</el-button>
		</template>
		<!-- 特殊表格内容 -->
		<template #tableContent="{ scope, column }">
			<div class="demo-image__preview" v-if="column.prop === 'img'">
				<el-image :preview-teleported="true" style="width: 100px; height: 100px" :src="$fullUrl($banseUrl,scope.row.img)"
					:preview-src-list="[$fullUrl($banseUrl,scope.row.img)]">
				</el-image>
		   </div>
			<span v-if="column.prop === 'user_id'">
				{{getObj(list_user,scope.row.user_id).nickname}}
			</span>
			<span v-if="column.prop === 'state'">
				<span v-if="scope.row.state === '待退款'">
					<el-button type="danger" @click="set_state(scope.row)" round>待退款</el-button>
				</span>
				<div v-else>
					{{scope.row.state}}
				</div>
			</span>
		  <span v-if="column.prop === 'create_time'">{{
			formatDate(scope.row.create_time)
		  }}</span>
		  <span v-if="column.prop === 'update_time'">{{
			formatDate(scope.row.update_time)
		  }}</span>
		</template>
		<template #tableContent2="{ scope, column }">
			<span v-if="column.prop === 'user_id'">
				{{ column.label }}：{{getObj(list_user,scope.user_id).nickname}}
			</span>
			<span v-if="column.prop === 'state'">{{ column.label }}：
				<span v-if="scope.tate === '待退款'">
					<el-button type="danger" @click="set_state(scope)" round>待退款</el-button>
				</span>
				<div v-else>
					{{scope.state}}
				</div>
			</span>
		  <span v-if="column.prop === 'create_time'">{{ column.label }}：{{
			formatDate(scope.create_time)
		  }}</span>
		  <span v-if="column.prop === 'update_time'">{{ column.label }}：{{
			formatDate(scope.update_time)
		  }}</span>
		</template>
	  </baseTable>
	  <el-dialog title="退款审批"  v-model="refund_view" width="30%" :before-close="handleClose">
			<span>
				<el-form ref="form" :model="form" label-width="80px">
					<el-form-item label="退款状态">
						<el-select v-model="form.state">
							<el-option label="待退款" value="待退款" :key="1"></el-option>
							<el-option label="已退款" value="已退款" :key="2"></el-option>
							<el-option label="已拒绝" value="已拒绝" :key="3"></el-option>
						</el-select>
					</el-form-item>
				</el-form>
			</span>
			 <template #footer>
          <span  class="dialog-footer">
            <el-button @click="refund_view = false; form.state='' ">取消</el-button>
				<el-button type="primary" @click="toSet()">提交</el-button>
          </span>
        </template>
       </el-dialog>
	   <!-- 支付弹窗 -->
	   <detailsDialog :detailObj="detailObj"   v-model:dialogVisible="dialogDetailVisible" @handleSuccess='handleSuccess'></detailsDialog>
	</el-main>
  </template>
  <script setup>
  import detailsDialog from "../pay/details.vue";
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { useRouter } from "vue-router";
  import moment from 'moment'
  let router = useRouter();
  import {
    $fullUrl,
	formatDate,
	$banseUrl,
	$check_action,
	$check_option,
  } from "@/utils/utils.js";
  import { $post, $get } from "@/api/Api.js";
  import { ref, toRefs, computed, onMounted } from "vue";
  import storageHelper from "@/libs/StorageHelper";
  let table = ref("order");
  let field = ref("order_id");
  let url_get_list = ref("/api/order/get_list");
  let url_del = ref("/api/order/del?");
  let user_group = storageHelper.getUserInfo().user_group;
  let user_id = storageHelper.getUserInfo().user_id;
  /// 获取用户信息
  let list_user = ref([]);
  let refund_view = ref(false);
  let list_state = ref(["待付款", "已付款"]);
  //支付详情
  let detailObj=ref({})
  let dialogDetailVisible=ref(false)
  // 头部搜索// 搜索
  let formInline = ref({
	state: "",
	order_number: "",
	name: "",
	contact_name: "",
  });
  let vm=ref({
    id: "order_id",
	img:'img',
})
  // 列名
  const columns = [
	{ prop: "title", label: "商品名称" },
	{ prop: "order_number", label: "订单号" },
	{ prop: "img", label: "商品图片" },
	{ prop: "price", label: "价格" },
	{ prop: "price_ago", label: "原价" },
	{ prop: "num", label: "购买数量" },
	{ prop: "price_count", label: "总价" },
	{ prop: "contact_name", label: "联系人名称" },
	{ prop: "contact_address", label: "联系人地址" },
	{ prop: "state", label: "订单状态" },
	{ prop: "user_id", label: "买家" },
	{ prop: "remark", label: "备注" },
	{ prop: "create_time", label: "创建时间" },
	{ prop: "update_time", label: "更新时间" },
  ];
  // 刷新table
  let isRefresh = ref(false);
  //批量勾选数据
  let selectList = ref([]);
  //点击当前行数据
  let currentRowTableProduct = ref({});
  //表格勾选回调
  let handleSelectionChange = (val) => {
	selectList.value = val.map((item) => {
	  return item.order_id;
	});
  };
  //点击当前行
  let handleCurrentChangeNew = (val) => {
	currentRowTableProduct.value = val;
  };
	// 查询数组对象某个是否包含某个值,返回对应对象
	let getObj=(arr,val) =>{
		let obj = arr.find(item => item.user_id == val)
		if(obj){
			return obj;

		}else{

			return'-'
		}
		
	}
    //获取对象之前
   let get_list_before=(param)=>{
	    if (user_group!=='管理员'){
          if ($check_option('/goods/table', 'seller')){
            url_get_list.value = "/api/order/get_business_order_list?user_id="+user_id;
          }else {
            url_get_list.value = "/api/order/get_list?user_id="+user_id;
          }
		  isRefresh.value = true;
        }
    }
	// 支付
	let toPay=(val)=>{
		console.log(val)
      detailObj.value=val
	  dialogDetailVisible.value=true
	}
	// 支付成功回调
	let handleSuccess=()=>{
		isRefresh.value = true;
	}
	
  // 批量删除删除
  let delInfo = () => {
	ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
	  confirmButtonText: "确定",
	  cancelButtonText: "取消",
	  type: "warning",
	})
	  .then(() => {
		selectList.value.map((item) => {
		  delFun(item);
		});
	  })
	  .catch(() => {
		ElMessage({
		  type: "info",
		  message: "取消操作",
		});
	  });
  }
    //确认关闭--退款审批
    let handleClose=(done)=> {
		ElMessageBox.confirm.confirm('确认关闭？')
		 .then(() => {
			done()
		}).catch(() => {
			// catch error
		})
	}
	//修改状态--退款审批
	let toSet=()=> {
		refund_view.value = false;
					// this.set({
					// 	state: this.form.state
					// }, {
					// 	order_id: this.form.order_id
					// });
		form.value.state = ""
		isRefresh.value = true;
	}
	// 显示退款窗口
	let set_state=(o) =>{
		form.value  = Object.assign({}, o);
		refund_view.value  = 1;
	}
    //获取用户
    let get_list_user = async() => {
	  var json =  await $get('/api/user/get_list')
  	    if (json.result) {
			list_user.value = json.result.list;
		} else if (json.error) {
			console.error(json.error);
		}

	}
	
	let addLogi=(data) =>{
		// var today = new Date();
        var currentDate = moment().format('YYYY-MM-DD');
		var postData = {
			"order_number":data.order_number
			,"product_name":data.title
			,"purchase_quantity":data.num
			,"total_transaction_amount":data.price_count
			,"the_date_of_issuance":currentDate
			,"delivery_number":Number(Math.random().toString().substr(3,12) + Date.now()).toString(36)
			,"shipping_address":data.contact_address
			,"delivery_status":"待取货"
			,"signing_status":"待签收"
			,"logistics_delivery_id":0
			,"contact_name":data.contact_name
			,"merchant_id":data.merchant_id
			,"ordinary_users":data.user_id
		}
		$post("/api/logistics_delivery/add?", postData).then((json, status) => {
			if (json.result) {
			    $post("/api/order/set?order_id="+data.order_id, {"delivery_state":"已配送"}).then((json_order, status) => {
					if (json_order.result) {
						ElMessage.success("添加成功！");
					    setTimeout(() => {
							router.push('../logistics_delivery/table')
						}, 2000)
					} else if (json_order.error) {
						ElMessage.error(json_order.error.message);
					}
		      });
			} else if (json.error) {
				ElMessage.error(json.error.message);
			}
		});
	}
  // 调用删除方法
  let delFun = (id) => {
	$get(url_del.value + "order_id=" + id).then((json) => {
	  if (json.result) {
		ElMessage.success("删除成功");
	  } else if (json.error) {
		ElMessage.error(json.error.order);
	  }
	  isRefresh.value = true;
	});
  };
  
  let table_class = ({ row, column, rowIndex, columnIndex }) => {
	return "table_class";
  };
  // 搜索
  let onSubmit = () => {
	isRefresh.value = true;
  };
  // 重置
  let onReset = (refresh) => {
	formInline.value = {
		state: "",
		order_number: "",
		name: "",
		contact_name: "",
	};
	isRefresh.value = refresh;
  };
  
  onMounted(() => {
	get_list_user()
	get_list_before()

  });
  </script>
  <style lang="less" scoped>
  .div-form {
	padding: 10px;
  }
  </style>
  